const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')

const Image = mongoose.model('Image')
const User = mongoose.model('User')
const Comment = mongoose.model('Comment')
const bcrypt = require('bcryptjs')

router.get('/', async (ctx, next) => {
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const leastCom = await Comment.find({})
    .sort({createdAt: -1}).limit(3)
  const stats = await statsfn()
  await ctx.render('index', {
    title: '图片分享',
    images, stats, username: ctx.session.username, nickname: ctx.session.nickname, userId: ctx.session.userId,leastCom
  })
})

router.get('/login', async ctx => {
  await ctx.render('login', {})
})

router.get('/register', async ctx => {
  await ctx.render('register', {})
})


router.post('/login', async ctx => {
  const { username, password } = ctx.request.body
  const user = await User.find({ username: `${username}`})
  const userinfo = user[0]
  console.log(userinfo)
  if(!userinfo){
    ctx.redirect('/', { user_error: 1 }) //user not exist.
  }else if(bcrypt.compareSync(password, userinfo.password)){
    ctx.session.username = username
    ctx.session.nickname = userinfo.nickname
    ctx.session.userId = userinfo._id
    ctx.redirect('/') //login ok.
  }else{
    ctx.redirect('/login', { pwd_error: 1 }) //password error.
  }
})

router.get('/logout', async ctx => {
  ctx.session.username = undefined
  ctx.redirect('/')
})

router.post('/register', async ctx => {
  let { username, nickname, password } = ctx.request.body
  const salt = bcrypt.genSaltSync(10)
  password = bcrypt.hashSync(password, salt)
  const user = await User.find({ username: `${username}`})
  if(!user) {
    console.log('user not exist!')
  } else {
    await User.create({
      username, nickname, password
    })
    ctx.redirect('/')
  }
})
module.exports = router
